package org.jmc.refmanager.web.wicket.page.admin;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.domain.service.UserManager;
import org.jmc.refmanager.jsr303validators.JSR303FormValidator;
import org.jmc.refmanager.security.SecurityHelper;
import org.jmc.refmanager.web.wicket.page.panel.ConfirmDeletePanel;
import org.jmc.refmanager.web.wicket.page.template.TemplatePage;
import org.springframework.security.authentication.encoding.PasswordEncoder;

/**
 */
@AuthorizeInstantiation(value={"ROLE_ADMIN", "ROLE_APPROVER"})
public class UserEditPage extends TemplatePage {
	@SpringBean(name="userManager")
	private UserManager userManager;

	@SpringBean(name = "passwordEncoder")
	private PasswordEncoder passwordEncoder;

	private ModalWindow confirmModal;

	/**
	 * @param parameters
	 */
	public UserEditPage(PageParameters parameters) {
		super(parameters);
		initComponents(parameters);
	}


	private void initComponents(PageParameters parameters) {
		add(new Label("pageTitle", "Modification d'un utilisateur"));
		
		final Integer userId = parameters.getAsInteger("id");
		
		IModel<User> model = new CompoundPropertyModel<User>(new LoadableDetachableModel<User>() {
			private static final long serialVersionUID = 1L;

			@Override
			protected User load() {
				return userManager.findById(userId);
			}
		});
		

		UserEditForm form = new UserEditForm("formEditCreate", model);
		add(form);
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback",
        		new ComponentFeedbackMessageFilter(form));
		add(feedback);
	}
	
	/**
	 * 
	 *
	 */
	final class UserEditForm extends Form<User> {
		private static final long serialVersionUID = 1L;

		public UserEditForm(String id, IModel<User> model) {
			super(id, model);
			
			final User user = getModelObject();
			
			boolean canEdit = SecurityHelper.isAdministrator();
			
			Label matriculeLabel = new Label("matricule", user.getMatricule());
			add(matriculeLabel);

			Label roleLabel = new Label("role", user.getRole().getDescription());
			add(roleLabel);

			OrgUnit validationScope = user.getValidationScope();
			String scope = validationScope==null?"N/A":validationScope.getLibCourt();
			Label validationScopeLabel = new Label("validationScope", scope);
			add(validationScopeLabel);

			PasswordTextField password = new PasswordTextField("password");
			password.setVisible(canEdit);
			add(password);

			Button btnCancel = new Button("btnCancel") {
		        	private static final long serialVersionUID = 1L;
		        	@Override
		        	public void onSubmit() {
						// Affiche le message sur la page redirigee
		        		getSession().warn("L'utilisateur n'a pas été modifié");
	                    setResponsePage(UserFindPage.class);
	                }
	        };
	        btnCancel.setVisible(canEdit);
	        btnCancel.setDefaultFormProcessing(false);
	        add(btnCancel);

			Button btnClose = new Button("btnClose") {
	        	private static final long serialVersionUID = 1L;
	        	@Override
	        	public void onSubmit() {
                    setResponsePage(UserFindPage.class);
                }
	        };
	        btnClose.setVisible(!canEdit);
	        btnClose.setDefaultFormProcessing(false);
	        add(btnClose);

	        add(new Button("btnUpdate") {
				private static final long serialVersionUID = 1L;

				/* (non-Javadoc)
				 * @see org.apache.wicket.markup.html.form.Button#onSubmit()
				 */
				@Override
				public void onSubmit() {
					User user = (User) getForm().getModelObject();
    				String encodedNewPassword = passwordEncoder.encodePassword(user.getPassword(), null);
	        		// Appel au changement de mot de passe
    				userManager.changePassword(user, null, encodedNewPassword);
					
					// Affiche le message sur la page redirigee
					getSession().info("L'utilisateur a été modifié avec succès");
					setResponsePage(UserFindPage.class);
				}
	        }.setVisible(canEdit));
	        
	        add(new JSR303FormValidator());

			confirmModal = new ModalWindow("confirmModal");
	        // Style graphique : CSS_CLASS_GRAY ou CSS_CLASS_BLUE
			confirmModal.setCssClassName(ModalWindow.CSS_CLASS_BLUE);
	        // Type du masque : TRANSPARENT ou SEMI_TRANSPARENT
			confirmModal.setMaskType(ModalWindow.MaskType.TRANSPARENT);
			confirmModal.setTitle("Confirmation");
			confirmModal.setInitialWidth(400);
			confirmModal.setWidthUnit("px");
			confirmModal.setResizable(false);
			confirmModal.setUseInitialHeight(false);
			
			add(confirmModal);

			AjaxLink<Integer> btnDelete = new AjaxLink<Integer>("btnDelete",
					new PropertyModel<Integer>(user, "id")) {
				private static final long serialVersionUID = 1L;

				@Override
				public void onClick(final AjaxRequestTarget ajaxRequestTarget) {
					confirmModal.setContent(new ConfirmDeletePanel(confirmModal.getContentId(), String.format(
							"Etes vous sûr de supprimer l'utilisateur '%s'?",
							user.getMatricule())) {
						private static final long serialVersionUID = 1L;

						@Override
						protected void onConfirm() {
							Integer userId = getModelObject();
							userManager.remove(userId);
							getSession().info("L'utilisateur a été supprimé avec succès");
							setResponsePage(UserFindPage.class);
						}
					});
					// Desactivation du message lie au post et changement de
					// fenetre
					ajaxRequestTarget
							.appendJavascript("Wicket.Window.unloadConfirmation = false;");
					confirmModal.show(ajaxRequestTarget);
				}
			};
			
			add(btnDelete);
		}
		
	}
}

